package com.lihao.baselibrary.utils;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.lihao.baselibrary.R;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * title: DownTask.java<br>
 * Copyright: Copyright ©2014-8-4<br>
 * Company: CQ digwei<br>
 * description: 文件下载<br>
 *
 * @author kougin
 * @version v1.0
 * @date 2014-8-4
 */
public class DownTask extends AsyncTask<String, Integer, String> {
    private Context mContext;
    private DownTaskCancelListner cancleListener = null;
    private long length;
    private boolean running = false;
    private ProgressBar progreassBar;
    private int mb = 1024 * 1024;
    private TextView showDownload;
    private AlertDialog dlg;
    private String mPath;
    private TextView mtitle;

    public interface DownTaskCancelListner {
        public void downTaskCancelNotify();
    }

    public void setCancleListener(DownTaskCancelListner cancleListener) {
        this.cancleListener = cancleListener;
    }

    public DownTask(Context context, String path) {
        this.mContext = context;
        this.mPath = path;
        dlg = new AlertDialog.Builder(context).create();
        dlg.setCanceledOnTouchOutside(false);
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.update_version_dialog);
        progreassBar = (ProgressBar) window.findViewById(R.id.progreassBar);
        showDownload = (TextView) window.findViewById(R.id.progress_text);
        mtitle = (TextView) window.findViewById(R.id.dialog_top);
        TextView cancel = (TextView) window.findViewById(R.id.alert_dialog_confirm_btn);
        mtitle.setText("版本更新中...");
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onCancelled();
                dlg.dismiss();
                if (cancleListener != null) {
                    cancleListener.downTaskCancelNotify();
                }
            }
        });
    }

    public void setMax(int lenth) {
        progreassBar.setMax((int) lenth);
    }

    @Override
    protected String doInBackground(String... params) {
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(params[0]);
        HttpResponse response = null;
        FileOutputStream fileOutputStream = null;
        InputStream is = null;
        File file = null;
        String result = null;
        try {
            String fileName = "";
            fileName = FileUtils.getPath(mContext, params[0], mPath);

            response = client.execute(get);
            if (response.getStatusLine().getStatusCode() != 200)
                throw new IOException("StatusCode!=200");
            HttpEntity entity = response.getEntity();
            length = entity.getContentLength();
            setMax((int) length);
            is = entity.getContent();
            if (is != null) {
                file = new File(fileName);
                file.createNewFile();
                fileOutputStream = new FileOutputStream(file);

                byte[] buf = new byte[1024];
                int ch = -1;
                int count = 0;
                while (running && (ch = is.read(buf)) != -1) {
                    fileOutputStream.write(buf, 0, ch);
                    count += ch;
                    if (length > 0) {
                        // 如果知道响应的长度，调用publishProgress（）更新进度
                        publishProgress(count);
                    }
                }
                fileOutputStream.flush();
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
                if (!running) {
                    if (file.exists()) {
                        file.delete();
                    }
                    return null;
                }
                File apk = new File(fileName);
                file.renameTo(apk);
                result = fileName;
            }

        } catch (ClientProtocolException e) {
            if (file != null && file.exists())
                file.delete();

        } catch (IOException e) {
            if (file != null && file.exists())
                file.delete();
            handler.sendEmptyMessage(0);
        } catch (Exception e) {
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e1) {
            }
        }
        return result;
    }

    @Override
    protected void onCancelled() {
        running = false;
        super.onCancelled();
    }

    @Override
    protected void onPreExecute() {
        running = true;
        dlg.show();
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(String result) {
        try {
            dlg.dismiss();
        } catch (Exception e) {
        }

        dlg.dismiss();

        if (result != null) {
            installPrograme(result);
        }

        if (cancleListener != null) {
            cancleListener.downTaskCancelNotify();
        }
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        // 更新进度
        progreassBar.setProgress(values[0]);
        double a = values[0] * 1.0 / mb;
        showDownload.setText("已下载：" + Utils.formatNumber(a) + "MB/"
                + Utils.formatNumber((length * 1.00) / mb) + "MB");
    }

    protected void installPrograme(String fileName) {
        Intent i = new Intent();
        i.setAction(Intent.ACTION_VIEW);
        File apkFile = new File(fileName);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        mContext.startActivity(i);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    Toast.makeText(mContext, "下载失败，请稍后再试", Toast.LENGTH_SHORT).show();
                    if (cancleListener != null) {
                        cancleListener.downTaskCancelNotify();
                    }
                    break;
            }
        }

    };
}
